# Maintainer: Maciej Suminski <maciej.suminski@cern.ch>
# Contributor: Unai Martinez-Corral <unai.martinezcorral@ehu.eus>

_realname=ngspice
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=41
pkgrel=1
pkgdesc="Mixed-level/Mixed-signal circuit simulator based on Spice3f5, Cider1b1, and Xspice (mingw-w64)"
url='https://ngspice.sourceforge.io/'
license=('BSD')
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
groups=("${MINGW_PACKAGE_PREFIX}-eda")
conflicts=(${MINGW_PACKAGE_PREFIX}-${_realname}-git)
replaces=(${MINGW_PACKAGE_PREFIX}-${_realname}-git)
depends=(
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
  $([[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-openmp")
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-autotools"
  "${MINGW_PACKAGE_PREFIX}-cc"
)
source=(
  "https://downloads.sourceforge.net/project/${_realname}/ng-spice-rework/${pkgver}/${_realname}-${pkgver}.tar.gz"
  "https://downloads.sourceforge.net/project/${_realname}/ng-spice-rework/${pkgver}/${_realname}-doc-${pkgver}.tar.gz"
  "no-explicit-lstdc++.patch"
)
sha256sums=('1ce219395d2f50c33eb223a1403f8318b168f1e6d1015a7db9dbf439408de8c4'
            '15bf35cbc832931a139da9eb084d20e0035f67398960366b40bbef064bafa2ba'
            '57f0f6e79faead15b0e1338a32c414b851997edb716467e8c0bc9a10df423582')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/no-explicit-lstdc++.patch"
  autoreconf -fiv
}

build() {
  mkdir -p "${srcdir}/build-shared-${MSYSTEM}" && cd "${srcdir}/build-shared-${MSYSTEM}"

  # FS#45230, create so lib
  # shared lib sets flags and modifies headers, needs dedicated pass
  # adding --with-readline disables libngspice-0.dll
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    LDFLAGS+=" -lomp"
  fi
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --disable-debug \
    --enable-openmp \
    --enable-xspice \
    --enable-cider \
    --with-ngshared
  make

  mkdir -p "${srcdir}/build-static-${MSYSTEM}" && cd "${srcdir}/build-static-${MSYSTEM}"

  # gcc is being weird
  LDFLAGS+=" -lgdi32"
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --disable-debug \
    --enable-xspice \
    --enable-cider \
    --enable-openmp \
    --with-wingui
  make
}

package() {
  cd "${srcdir}/build-static-${MSYSTEM}"
  make DESTDIR="${pkgdir}" install

  cd "${srcdir}/build-shared-${MSYSTEM}"
  make DESTDIR="${pkgdir}" install

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYING" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
